package com.ft.typehandler;

import com.ft.model.enums.OrderStatusEnum;
import com.ft.util.EnumUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author huangxiao
 * @date 2018/7/27 16:27
 */
public class OrderStatusEnumTypeHandler extends BaseTypeHandler<OrderStatusEnum> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, OrderStatusEnum parameter,
                                    JdbcType jdbcType) throws SQLException {
        if (jdbcType == null || jdbcType == JdbcType.VARCHAR) {
            // 如果数据库的字段类型是 varchar, 就使用枚举的 name 来存储
            ps.setString(i, parameter.name());
        } else {
            // 否则使用 getCode 返回的 int 值来存储
            ps.setInt(i, parameter.getId());
        }
    }

    @Override
    public OrderStatusEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return EnumUtils.toEnum(OrderStatusEnum.class, rs.getObject(columnName));
    }

    @Override
    public OrderStatusEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return EnumUtils.toEnum(OrderStatusEnum.class, rs.getObject(columnIndex));
    }

    @Override
    public OrderStatusEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return EnumUtils.toEnum(OrderStatusEnum.class, cs.getObject(columnIndex));
    }
}
